﻿namespace BEGDC.CC.Web.UserControls.OCV
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;

    using BEGDC.CC.BL.CCFlow.OCV;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.Utility.Castle;

    /// <summary>
    ///		Summary description for CATPSOApprove.
    /// </summary>
    public class LvLeaderApproval : BaseOCV
    {
        protected System.Web.UI.WebControls.Label Label1;
        protected System.Web.UI.WebControls.Button btnQuery;
        protected System.Web.UI.WebControls.Button btnReject;
        protected System.Web.UI.WebControls.Button btnSubmit;
        protected System.Web.UI.WebControls.Button btnReply;
        protected System.Web.UI.WebControls.Button btnClose;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.TextBox tbIsNeedNextLvApprover;
        protected System.Web.UI.WebControls.TextBox tbLvApprover;
        protected OCVCtrl uclOCV;
        //protected BEGDC.CC.Web.UserControls.CV.CVPrintCtrl cvPrintCtrl;

        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }

        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                uclOCV.isReadOnly = true;
                this.btnQuery.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["AppID"] + ");");
                this.btnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["FlowID"] + ");");
                this.btnReject.Attributes.Add("onclick", "javascript:OpenCommentPane();");
                this.btnSubmit.Attributes.Add("onclick", "javascript:OnSubmit(" + Request.QueryString["FlowID"] + ");");
                this.btnClose.Attributes.Add("onclick", "javascript:SimpleCloseWindow();");

                IQuery query = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = query.QueryFlowInstance(this.AppID);
                if (flowInstance != null && flowInstance.CurrentActiveStep.StepCode != BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv1Approval)
                {
                    if (query.IsNeedNextLvApprover(flowInstance.FlowID, flowInstance.CurrentActiveStep.StepCode))
                        this.tbIsNeedNextLvApprover.Text = "Yes";
                }
            }
            ButtonStatusSetting();
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnQuery.Click += new EventHandler(btnQuery_Click);
            this.btnReply.Click += new EventHandler(this.btnReply_Click);
            this.btnSubmit.Click += new EventHandler(this.btnSubmit_Click);
            this.btnReject.Click += new EventHandler(this.btnReject_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void btnReject_Click(object sender, EventArgs e)
        {
            try
            {
                IOCV ocrService = AppContainer.Instance[ServiceConst.OCVService] as IOCV;
                ocrService.DepartmentHeadApprove(Convert.ToInt64(Request.QueryString["FlowID"]), CVTransitionList.Reject, WebUtility.DeCodeString(Server, tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script><script>window.close();</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }

        #region Submit

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                IOCV OCVService = AppContainer.Instance[ServiceConst.OCVService] as IOCV;
                BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;

                Employee nextLvApprover = null;
                string lv3ApproverNo = "";
                string lv2ApproverNo = "";
                string lv1ApproverNo = "";

                if (!string.IsNullOrEmpty(this.tbLvApprover.Text) && this.tbLvApprover.Text.Contains("_"))
                {
                    string[] temp = this.tbLvApprover.Text.Split('_');
                    lv3ApproverNo = temp[0];
                    lv2ApproverNo = temp[1];
                    lv1ApproverNo = temp[2];
                }

                Employee currentUser = ((CCIdentity)HttpContext.Current.User.Identity).UserInfo;
                //if (!string.IsNullOrEmpty(this.tbLvApprover.Text) && this.Step != BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv1Approval)
                //{
                //    nextLvApprover = userService.GetUserByID(this.tbLvApprover.Text);
                //}
                //OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, nextLvApprover, this.Step, string.Empty);

                if (string.IsNullOrEmpty(this.tbLvApprover.Text) ||
                    this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv1Approval)
                {
                    OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, nextLvApprover, this.Step, string.Empty);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv2Approval)
                {
                    if (!string.IsNullOrEmpty(lv3ApproverNo) || !string.IsNullOrEmpty(lv2ApproverNo) || string.IsNullOrEmpty(lv1ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv2 approval could not be performed. 2级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV2LeadApproval(OCVService, userService, currentUser, lv1ApproverNo);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv3Approval)
                {
                    if (!string.IsNullOrEmpty(lv3ApproverNo) || string.IsNullOrEmpty(lv2ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv3 approval could not be performed. 3级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV3LeadApproval(OCVService, userService, currentUser, lv2ApproverNo, lv1ApproverNo);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCV_Lv4Approval)
                {
                    if (string.IsNullOrEmpty(lv3ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv4 approval could not be performed. 4级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV4LeadApproval(OCVService, userService, currentUser, lv3ApproverNo, lv2ApproverNo, lv1ApproverNo);
                }
                else
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('Level approval could not be performed. 级别审批不能进行!');</script>");
                    return;
                }

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script><script>window.close();</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }


        #region Submit LV4 Lead Approval

        private void SubmitLV4LeadApproval(IOCV OCVService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, string lv3ApproverNo, string lv2ApproverNo, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv3ApproverNo)) return;

            if (lv3ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv3ApproverNo);
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, nextLvApprover, WorkTransition.OCV_Lv4Approval, string.Empty);
            }
            else
            {
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, currentUser, WorkTransition.OCV_Lv4Approval, string.Empty);
                if (string.IsNullOrEmpty(lv2ApproverNo))
                {
                    OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, null, WorkTransition.OCV_Lv3Approval, string.Empty);
                }
                else
                {
                    this.SubmitLV3LeadApproval(OCVService, userService, currentUser, lv2ApproverNo, lv1ApproverNo);
                }
            }
        } 

        #endregion

        #region Submit LV3 Lead Approval

        private void SubmitLV3LeadApproval(IOCV OCVService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, string lv2ApproverNo, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv2ApproverNo)) return;

            if (lv2ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv2ApproverNo);
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, nextLvApprover, WorkTransition.OCV_Lv3Approval, string.Empty);
            }
            else
            {
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, currentUser, WorkTransition.OCV_Lv3Approval, string.Empty);
                if (string.IsNullOrEmpty(lv1ApproverNo))
                {
                    OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, null, WorkTransition.OCV_Lv2Approval, string.Empty);
                }
                else
                {
                    this.SubmitLV2LeadApproval(OCVService, userService, currentUser, lv1ApproverNo);
                }
            }
        }

        #endregion

        #region Submit LV2 Lead Approval

        private void SubmitLV2LeadApproval(IOCV OCVService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv1ApproverNo)) return;

            if (lv1ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv1ApproverNo);
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, nextLvApprover, WorkTransition.OCV_Lv2Approval, string.Empty);
            }
            else
            {
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, currentUser, WorkTransition.OCV_Lv2Approval, string.Empty);
                OCVService.SubmitLVLeadApproval(Convert.ToInt64(Request.QueryString["FlowID"]), this.AppID, OCVTransitionList.Approve, null, WorkTransition.OCV_Lv1Approval, string.Empty);
            }
        }

        #endregion

        #endregion

        private void ControlStatusSetting(Accessibility access)
        {
            if (access == Accessibility.Readonly)
            {
                this.DisableChildrenControls(this);
            }
        }

        private void Btn_Export_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ExcelTool.ICCExcelExport excelExport = new ExcelTool.ExportCVForm();
                excelExport.Export(this.Page, this.AppID);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");
            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
            }

        }

        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.btnSubmit.Visible = this.Access.IsButtonVisible(CVTransitionList.Approve);
            this.btnReject.Visible = this.Access.IsButtonVisible(CVTransitionList.Reject);
            this.btnReply.Visible = this.Access.IsButtonVisible(CVTransitionList.Reply);
            this.btnQuery.Visible = this.Access.IsButtonVisible(CVTransitionList.Query);
            this.uclOCV.cvPrintCtrl.ProcessType = WorkflowTypes.OCV;
            this.uclOCV.cvPrintCtrl.Visible = this.Access.IsButtonVisible(OCVTransitionList.Copy);
        }

        private void btnReply_Click(object sender, EventArgs e)
        {
            try
            {
                IOCV ocrService = AppContainer.Instance[ServiceConst.OCVService] as IOCV;
                if (this.tbOperationFlag.Text == "reply")
                    ocrService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script><script>window.close();</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }

        void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag.Text == "query")
                {
                    IOCV ocvService = AppContainer.Instance[ServiceConst.OCVService] as IOCV;
                    ocvService.Query(Convert.ToInt64(Request.QueryString["FlowID"]), this.tbOperationContent.Text, Session["Comment"].ToString());
                }
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }
    }
}
